#include "qlogview.h"

#include "../../libs/core/qlogdatabaseview.h"
#include "../../libs/core/qsoftcore.h"
#include "../../libs/device/qdevicemanager.h"

#include <QVBoxLayout>
#include <QMessageBox>
#include <QApplication>

QLogView::QLogView(tagDeviceInfo *info, QWidget *parent):
    QWidget(parent),
    m_log_view(new QLogDatabaseView),
    m_device_info(*info),
    m_progress_dialog(new QProgressDialog(this))
{
    QVBoxLayout *v=new QVBoxLayout;
    v->setMargin(0);
    v->setSpacing(0);

    v->addWidget(m_log_view);

    setLayout(v);


    QList<QAction*> list;
    QAction* ac;

    ac=new QAction(this);
    ac->setIcon(QIcon(":/images/device_database_download.png"));
    ac->setText(tr("Download"));
    connect(ac,SIGNAL(triggered()),this,SLOT(load_log()));
    list.append(ac);

    m_log_view->set_tool_bar(list);

    m_progress_dialog->setVisible(false);


    m_device_manager=QSoftCore::get_core()->get_device_manager();
}

void QLogView::load_log()
{
    connect(m_device_manager,SIGNAL(database_count(int)),this,SLOT(database_count(int)));
    connect(m_device_manager,SIGNAL(database_end()),this,SLOT(database_end()));
    connect(m_device_manager,SIGNAL(database_error(QString)),this,SLOT(database_error(QString)));
    connect(m_device_manager,SIGNAL(database_next()),this,SLOT(database_next()));
    m_progress_dialog=new QProgressDialog(this,Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    m_progress_dialog->setWindowTitle(tr("Download"));
    m_progress_dialog->setValue(0);
    m_progress_dialog->setCancelButton(NULL);
    m_device_manager->start_load_database(m_device_info.m_uuid,"log_data.db");
    m_progress_dialog->exec();
    delete m_progress_dialog;
}

void QLogView::database_count(int count)
{
    m_progress_dialog->setRange(0,count);
}

void QLogView::database_end()
{
    m_log_view->load(qApp->applicationDirPath()+"/temp/"+m_device_info.m_uuid+"/log_data.db");

    disconnect(m_device_manager,SIGNAL(database_count(int)),this,SLOT(database_count(int)));
    disconnect(m_device_manager,SIGNAL(database_end()),this,SLOT(database_end()));
    disconnect(m_device_manager,SIGNAL(database_error(QString)),this,SLOT(database_error(QString)));
    disconnect(m_device_manager,SIGNAL(database_next()),this,SLOT(database_next()));
}

void QLogView::database_error(const QString &error)
{
    m_progress_dialog->close();
    disconnect(m_device_manager,SIGNAL(database_count(int)),this,SLOT(database_count(int)));
    disconnect(m_device_manager,SIGNAL(database_end()),this,SLOT(database_end()));
    disconnect(m_device_manager,SIGNAL(database_error(QString)),this,SLOT(database_error(QString)));
    disconnect(m_device_manager,SIGNAL(database_next()),this,SLOT(database_next()));
    QMessageBox::critical(this,tr("Error"),error);
}

void QLogView::database_next()
{
    m_progress_dialog->setValue(m_progress_dialog->value()+1);
}
